package com.fenxiangtech.mall.web.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fenxiangtech.mall.enums.ExceptionEnum;
import com.fenxiangtech.mall.exception.BaseException;
import com.fenxiangtech.mall.dto.ExceptionResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常处理器
 * @author zhangjiashun
 */
public class GlobalExceptionResolver implements HandlerExceptionResolver {

    private static Logger log = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object o, Exception e) {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        ExceptionResult result = new ExceptionResult();
        if (e instanceof BaseException) {
            BaseException baseException = (BaseException) e;
            result.setCode(baseException.getCode());
            result.setMsg(baseException.getMessage());
            response.setStatus(baseException.getStatusCode());
        } else {
            result.setCode(ExceptionEnum.UNKNOWN_ERROR.getCode());
            result.setMsg(ExceptionEnum.UNKNOWN_ERROR.getMsg());
            response.setStatus(ExceptionEnum.UNKNOWN_ERROR.getStatusCode());
            log.error(e.getMessage(), e);
        }
        result.setRequest(request.getMethod() + " " + request.getRequestURI());
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonString = objectMapper.writeValueAsString(result);
            response.getWriter().write(jsonString);
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
        return new ModelAndView();
    }
}
